import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-10-01
 * Time: 23:45
 */
class Solution15 {
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,-1,1};
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[][] dist = new int[m][n];
        // 初始化 dist 默认-1没搜索过 不为-1存的是最短距离
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                dist[i][j] = -1;
            }
        }
        Queue<int[]> q = new LinkedList<>();

        // 1.把所有源点加进去
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(mat[i][j] == 0) {
                    dist[i][j] = 0;
                    q.add(new int[]{i,j});
                }
            }
        }

        //2. 一层一层往外扩展
        while(!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1) {
                    dist[x][y] = dist[a][b]+1;
                    q.add(new int[]{x,y});
                }
            }
        }
        return dist;
    }
}
